package com.pangda.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pangda.common.constant.HttpStatusConstant;
import com.pangda.common.domain.PageResult;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.FileUtil;
import com.pangda.common.utils.UserContext;
import com.pangda.pojo.SysRole;
import com.pangda.pojo.SysUser;
import com.pangda.pojo.SysUserRole;
import com.pangda.pojo.data.SysRoleData;
import com.pangda.pojo.data.SysUserData;
import com.pangda.pojo.dto.SysUserDto;
import com.pangda.pojo.vo.SysUserVo;
import com.pangda.service.ISysRoleService;
import com.pangda.service.ISysUserRoleService;
import com.pangda.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xjy
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/")
    @ApiOperation("获取角色列表")
    public Map<String, Object> getRoleList() {
        List<SysRole> list = sysRoleService.list();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatusConstant.SUCCESS);
        map.put("msg", "success");
        map.put("roles", list);
        return map;
    }

    @PostMapping
    @ApiOperation("新增用户")
    public ResponseResult addUser(@RequestBody SysUserDto sysUserDto) {
        return sysUserService.addUser(sysUserDto);
    }

    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public PageResult<SysUserVo> list(PageResult pageResult, SysUserDto sysUserDto) {
        return sysUserService.searchUserList(pageResult, sysUserDto);
    }

    @GetMapping("/{userId}")
    @ApiOperation("获取用户信息")
    public Map<String, Object> getUser(@PathVariable("userId") Long userId) {
        return sysUserService.getUser(Math.toIntExact(userId));
    }

    @PutMapping
    @ApiOperation("修改用户")
    public ResponseResult updateUser(@RequestBody SysUserDto sysUserDto) {
        return sysUserService.updateUser(sysUserDto);
    }

    @PutMapping("/changeStatus")
    @ApiOperation("修改用户状态")
    public ResponseResult changeStatus(@RequestBody SysUserDto sysUserDto) {
        if (sysUserDto.getUserId() == null && sysUserDto.getStatus() == null) {
            return ResponseResult.error();
        }
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUser::getUserId, sysUserDto.getUserId())
                .set(SysUser::getStatus, sysUserDto.getStatus());
        return sysUserService.update(wrapper) ? ResponseResult.success() : ResponseResult.error("修改失败");
    }

    @PutMapping("/resetPwd")
    @ApiOperation("重置密码")
    public ResponseResult resetPwd(@RequestBody SysUserDto sysUserDto) {
        if (ObjectUtil.isEmpty(sysUserDto.getUserId()) && ObjectUtil.isEmpty(sysUserDto.getPassword())) {
            return ResponseResult.error();
        }
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(SysUser::getUserId, sysUserDto.getUserId())
                .set(SysUser::getPassword, sysUserDto.getPassword());
        return sysUserService.update(wrapper) ? ResponseResult.success() : ResponseResult.error("修改失败");
    }

    @DeleteMapping("/{userIds}")
    @ApiOperation("删除用户")
    public ResponseResult remove(@PathVariable List<Integer> userIds) {
        return sysUserService.removeByIds(userIds) ? ResponseResult.success() : ResponseResult.error();
    }

    @GetMapping("/importTemplate")
    @ApiOperation("导出用户模板")
    public Map<String, String> importTemplate() {
        return FileUtil.uploadFile(null, SysUserData.class, redisTemplate);
    }

    @PostMapping("/importData")
    @ApiOperation("导入用户数据")
    public ResponseResult importData(@RequestPart("file") MultipartFile file, String updateSupport) throws IOException {
        List<SysUserData> sysUserData = FileUtil.readExcel(file.getInputStream(), SysUserData.class);
        List<SysUser> sysUsers = BeanUtil.copyToList(sysUserData, SysUser.class);
        sysUsers.stream().map(sysUser -> {
            sysUser.setCreateTime(LocalDateTime.now());
            sysUser.setCreateBy(UserContext.getUser());
            return sysUser;
        }).collect(Collectors.toList());
        sysUserService.saveBatch(sysUsers);
        return ResponseResult.success();
    }

    @GetMapping("/listselect")
    @ApiOperation("获取用户下拉列表")
    public ResponseResult listselect(Integer deptId) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDeptId, deptId);
        List<SysUser> list = sysUserService.list(wrapper);
        return ResponseResult.success(list);
    }

    @GetMapping("/export")
    @ApiOperation("导出用户数据")
    public Map<String, String> export(PageResult pageResult) throws IOException {
        Page<SysUser> page = sysUserService.page(new Page<>(pageResult.getPageNum(), pageResult.getPageSize()));
        return FileUtil.uploadFile(page.getRecords(), SysUserData.class, redisTemplate);
    }
}
